package com.event.management.backend.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.nio.file.Paths;

/**
 * WebMvc配置类
 */
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {
    
    @Value("${file.upload.path:/uploads/images}")
    private String uploadPath;
    
    @Value("${file.access.path:/images}")
    private String accessPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决Swagger-ui资源无法访问的问题
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        
        // 解决Knife4j的js/css等静态资源无法被加载的问题
        registry.addResourceHandler("/swagger-resources")
                .addResourceLocations("classpath:/META-INF/resources/swagger-resources");
        registry.addResourceHandler("/swagger/**")
                .addResourceLocations("classpath:/META-INF/resources/swagger*");
        registry.addResourceHandler("/v2/api-docs/**")
                .addResourceLocations("classpath:/META-INF/resources/v2/api-docs");
        registry.addResourceHandler("/v3/api-docs/**")
                .addResourceLocations("classpath:/META-INF/resources/v3/api-docs");
                
        // 查找 eventsys 根目录
        String rootDir = findEventsysRootDir();

        // 确保上传路径正确
        String relativePath = uploadPath.startsWith("/") ? uploadPath.substring(1) : uploadPath;
        String absoluteUploadPath = Paths.get(rootDir, relativePath).toString();
        log.info("上传文件绝对路径: {}", absoluteUploadPath);

        // 确保上传目录存在
        File uploadDir = new File(absoluteUploadPath);
        if (!uploadDir.exists()) {
            if (!uploadDir.mkdirs()) {
                log.error("创建上传目录失败: {}", absoluteUploadPath);
            } else {
                log.info("成功创建上传目录: {}", absoluteUploadPath);
            }
        }
        
        // 配置文件资源访问路径
        String fileUrl = "file:" + absoluteUploadPath + File.separator;
        log.info("配置资源访问路径: {}", fileUrl);
        
        // 配置资源映射
        registry.addResourceHandler(accessPath + "/**")
                .addResourceLocations(fileUrl)
                .setCachePeriod(0); // 开发阶段禁用缓存
                
        log.info("图片访问路径映射: {} -> {}", accessPath + "/**", fileUrl);
    }
    
    /**
     * 配置跨域，解决前后端分离跨域问题
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    
    /**
     * 查找eventsys根目录
     * @return eventsys根目录的绝对路径
     */
    private String findEventsysRootDir() {
        String currentDir = System.getProperty("user.dir");
        String rootDir = currentDir;
        
        // 向上查找到eventsys目录作为根目录
        File dirFile = new File(currentDir);
        while (dirFile != null && !dirFile.getName().equals("eventsys")) {
            dirFile = dirFile.getParentFile();
            if (dirFile != null) {
                rootDir = dirFile.getAbsolutePath();
            }
        }
        
        // 如果找不到eventsys目录，使用当前目录
        if (dirFile == null) {
            log.warn("未找到eventsys目录，使用当前目录: {}", currentDir);
            return currentDir;
        }
        
        return rootDir;
    }
} 